<template>
  <div class="video-container">
    <video
      ref="videoPlayer"
      width="600"
      height="400"
      controls
      @loadedmetadata="onLoadedMetadata"
      @play="onPlay"
      @pause="onPause"
      @ended="onEnded"
    >
      <source poster="https://static.rangrang.cn/frontend-file/H5/video/rr_tips_video.png"
        src="https://static.rangrang.cn/frontend-file/H5/video/rr_tips_video.mp4" type="video/mp4" />
      Your browser does not support the video tag.
    </video>
    <div class="countdown" v-if="duration > 0">{{ countdown }}</div>
    <div class="controls">
      <button @click="togglePlay">
        {{ isPlaying ? 'Pause' : 'Play' }}
      </button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      videoSrc: 'path/to/your/video.mp4', // 替换为你的视频路径
      duration: 0, // 视频总时长（秒）
      currentTime: 0, // 当前播放时间（秒）
      countdown: 0, // 倒计时
      intervalId: null, // 定时器ID
      isPlaying: false, // 是否正在播放
    };
  },
  mounted() {
    this.$refs.videoPlayer.play(); // 页面加载时自动播放视频
    this.isPlaying = true;
  },
  methods: {
    // 事件监听器用于处理视频元数据加载
    onLoadedMetadata() {
      this.duration = Math.floor(this.$refs.videoPlayer.duration);
      this.countdown = this.duration;
      // 初始化倒计时
      this.startCountdown();
    },
    // 播放
    onPlay() {
      this.isPlaying = true;
      this.startCountdown();
    },
    // 暂停
    onPause() {
      this.isPlaying = false;
      clearInterval(this.intervalId);
    },
    // 结束事件
    onEnded() {
      this.isPlaying = false;
      clearInterval(this.intervalId);
      this.countdown = 0;
    },
    // 切换播放和暂停状态
    togglePlay() {
      if (this.isPlaying) {
        this.$refs.videoPlayer.pause();
      } else {
        this.$refs.videoPlayer.play();
      }
    },
    // 启动或更新倒计时
    startCountdown() {
      if (this.isPlaying && this.duration > 0) {
        this.intervalId = setInterval(() => {
          this.currentTime = this.$refs.videoPlayer.currentTime;
          this.countdown = Math.floor(this.duration - this.currentTime);
        }, 1000);
      }
    },
  },
};
</script>

<style scoped>
.video-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.countdown {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
}

.controls {
  margin-top: 10px;
}
</style>